<?php

namespace ticky;

class redis {

    protected $handler = null;
    protected $config = [
        'host' => '127.0.0.1', // redis主机
        'port' => 6379, // redis端口
        'password' => '', // 密码
        'select' => 0, // 操作库
        'expire' => 3600, // 有效期(秒)
        'timeout' => 0, // 超时时间(秒)
        'persistent' => true, // 是否长连接
        'prefix' => '', // 前缀
    ];

    public static function &instance() {
        static $object;
        if (empty($object)) {
            $object = new self();
        }
        return $object;
    }

    public function __construct($config = []) {
        if (count($config) <= 0) {
            $config = config::get('redis');
        }
        $this->config = array_merge($this->config, $config);
    }

    // 链接redis服务器
    public function connect($config = []) {
        // 检测php环境
        if (!extension_loaded('redis')) {
            app::halt('not support:redis');
        }
        $this->config = array_merge($this->config, $config);
        $this->handler = new \Redis;
        // 建立连接
        $func = $this->config['persistent'] ? 'pconnect' : 'connect';
        $this->handler->$func($this->config['host'], $this->config['port'], $this->config['timeout']);
        if ('' != $this->config['password']) {
            $this->handler->auth($this->config['password']);
        }
        if (0 != $this->config['select']) {
            $this->handler->select($this->config['select']);
        }
        return true;
    }

    // 关闭redis服务器
    public function close() {
        $this->handler->close();
        $this->handler = null;
        return true;
    }

    // 拼装完整键名
    private function key($key) {
        return $this->config['prefix'] . $key;
    }

    // 检测指定键名是否存在
    public function exists($key) {
        $key = $this->key($key);
        return $this->handler->exists($key);
    }

    // 设置
    public function set($key, $value, $expire = null) {
        $expire = isset($expire) ? $expire : $this->config['expire'];
        $key = $this->key($key);
        $value = is_numeric($value) ? $value : serialize($value);
        if (!$expire) {
            return $this->handler->set($key, $value);
        }
        return $this->handler->setex($key, (int) $expire, $value);
    }

    // 获取指定元素
    public function get($key) {
        $key = $this->key($key);
        $value = $this->handler->get($key);
        return is_numeric($value) ? $value : unserialize($value);
    }

    // 删除指定元素
    public function delete($key) {
        $key = $this->key($key);
        return $this->handler->delete($key);
    }

    // 清除所有元素
    public function clean() {
        return $this->handler->flushall();
    }

    // 自增
    public function inc($key, $value = 1) {
        $key = $this->key($key);
        return $this->handler->incrby($key, $value);
    }

    // 自减
    public function dec($key, $value = 1) {
        $key = $this->key($key);
        return $this->handler->decrby($key, $value);
    }

}
